package com.eop.managedBean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.operamasks.faces.annotation.Accessible;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.SaveState;
import org.operamasks.faces.component.form.impl.UISimpleHtmlEditor;
import org.operamasks.faces.component.form.impl.UITextArea;
import org.operamasks.faces.component.form.impl.UITextField;
import org.operamasks.faces.component.layout.impl.UIWindow;
import org.operamasks.faces.user.util.Browser;

import com.base.commonKey.CommonkeyReplace;
import com.base.commons.SpringBeanHolder;
import com.base.security.SecurityUserHolder;
import com.base.utils.IdUtils;
import com.eop.entity.Event;
import com.eop.entity.Minutes;
import com.eop.service.IEmergencyStageService;
import com.eop.service.IEventService;
import com.eop.service.IMinutesService;
import com.eop.service.ISpecialInforService;

@ManagedBean(name = "eop_welcomeBean", scope = ManagedBeanScope.REQUEST)
public class WelcomeBean {
	private Log logger = LogFactory.getLog(ListEventBean.class);
	private IEventService eventService = SpringBeanHolder
			.getBean("eventService");
	private IEmergencyStageService imsService = SpringBeanHolder
			.getBean("stageService");
	private ISpecialInforService spInfoService = SpringBeanHolder
			.getBean("specialInforService");
	private IMinutesService minutersServce = SpringBeanHolder
			.getBean("minutesService");

	@Inject
	private FacesContext context;

	@SaveState
	@Bind(id = "eventName")
	private String eventName = "";

	@SaveState
	@Bind(id = "stageName")
	private String stageName = "";

	@Bind(id = "minutesList")
	private String minutesList;

	@Bind(id = "minutesList", attribute = "binding")
	private HtmlOutputText minutesList_binding;

	@Bind(id = "eventId", attribute = "binding")
	protected UITextField eventId_binding;

	@Bind(id = "eventId", attribute = "value")
	private String eventId;

	@Bind(id = "minutesContent", attribute = "value")
	private String minutesContent;

	@Bind(id = "minutesContent", attribute = "binding")
	//private UISimpleHtmlEditor minutesContent_binding;
	private UITextArea minutesContent_binding;
	
	@SaveState
	private String headString = FacesContext.getCurrentInstance()
			.getExternalContext().getRequestContextPath();

	@SaveState
	private String id;

	@Accessible
	@SaveState
	private String windowTitle;

	@Bind
	private UIWindow repaireWin;
	@Bind(id = "eventTitle", attribute = "value")
	private String eventTitle_value;

	@Bind(id = "uMinCon", attribute = "value")
	private String uMinCon;
	@Bind(id = "minId", attribute = "value")
	private String minId;
	@Bind(id = "uMinCon", attribute = "binding")
	private UISimpleHtmlEditor uMinCon_binding;
	@Bind(id = "minId", attribute = "binding")
	protected UITextField minId_binding;

	@BeforeRender
	public void beforeRender(boolean isPostBack) {
		if (!isPostBack) {
			eventName = this.getEventValueString(eventService.getAllEvent());
			// stageName =
			// this.getStageValueString(imsService.getAllEmergencyStages());
			// infoName =
			// this.getSpecialValueString(spInfoService.getAllSpecialInformation());

			// if (id != null && !"".equals(id)) {
			// minutesList = this.getMinutesList();
			// }
		}
	}

	/**
	 * 获取应急事件列表
	 * 
	 * @param receviceNotifies
	 * @return
	 */
	private String getEventValueString(List<Event> receviceNotifies) {
		StringBuilder str = new StringBuilder();
		if (receviceNotifies != null && receviceNotifies.size() > 0) {
			str.append("<ul>");
			for (int i = 0; i < receviceNotifies.size(); i++) {
				Event event = receviceNotifies.get(i);
				String eventName = event.getEventName().replaceAll(
						"<(/?\\S+)\\s*?[^<]*?(/?)>", "<$1$2>");
				String eventAddress = "";
				if (event.getEventAddress() != null
						&& !"".equals(event.getEventAddress())) {
					eventAddress = event.getEventAddress().replaceAll(
							"<(/?\\S+)\\s*?[^<]*?(/?)>", "<$1$2>");
				}
				String remark = "";
				if (event.getEventRemark() != null
						&& !"".equals(event.getEventRemark())) {
					remark = event.getEventRemark().replaceAll(
							"<(/?\\S+)\\s*?[^<]*?(/?)>", "");
				}

				// replaceAll("SPAN", "").replaceAll(
				// "<(/?\\S+)\\s*?[^<]*?(/?)>", "<$1$2>");
				SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat
						.getInstance();
				formatter.applyPattern("yyyy-MM-dd HH:mm:ss");
				str
						.append("<li style=\"background-color:#CCCCCC;line-height:260%\">");
				str.append("<font size=\"3px\" color=\"#000033\">");
				if (event.getEventCreateDate() != null)
					str.append(" ["
							+ formatter.format(event.getEventCreateDate())
							+ "] ");
				str.append("<a href=\"javascript:window.open('" + headString
						+ "/modules/eop/showEvent.faces?id=" + event.getId()
						+ "');window.parent.refreshMainPage();\">");
				str.append("&nbsp;" + eventName);
				str.append("</a>");
				str
						.append("<font color=\"#000099\" size=\"3\">&nbsp;发生地点:</font>");
				if (!"".equals(eventAddress))
					str.append(eventAddress + ";");
				else
					str.append("无;");
				str
						.append("<font color=\"#000099\" size=\"3\">&nbsp;状态:</font>");

				if (event.getEventStatus() != null
						&& !"".equals(event.getEventStatus()))
					str.append(CommonkeyReplace.replaceCommonKey(event
							.getEventStatus())
							+ ";");
				else
					str.append("无;");
				str
						.append("<font color=\"#000099\" size=\"3\">&nbsp;适用范围:</font>"
								+ CommonkeyReplace.replaceCommonKey(event
										.getEventRangeB())
								+ "-"
								+ CommonkeyReplace.replaceCommonKey(event
										.getEventRangeS()));
				str
						.append("<font color=\"#000099\" size=\"3\">&nbsp;备注:</font>"
								+ remark);

				// str.append("</font>");

				str.append("<a href=\"javascript:showMinutes('" + event.getId()
						+ "');\">");
				str
						.append("<font color=\"#000099\" size=\"3\" style=\"border:double\">会议记录:</font>");

				str.append("</a>");

				str.append("</font>");
				str.append("</li>");
				// str.append("<br/>");
			}
			str.append("</ul>");
		}
		return str.toString();
	}

	@Action(id = "showRepaire")
	public void showRepaire() {
		id = context.getExternalContext().getRequestParameterMap().get("id");
		if (id != null && !"".equals(id)) {
			Event event = eventService.getEventById(id);
			windowTitle = "会议记录：     " + event.getEventName();
			Browser.execClientScript("showRepWindow();");
			repaireWin.repaint();

			minutesList = "";
			minutesList_binding.repaint();

			minutesList = this.getMinutesList();
			Browser.execClientScript("refDiv();");
		}
	}
	
	

	public String getMinutesList() {
		StringBuilder str = new StringBuilder();
		if (id == null || "".equals(id)) {
			if (eventId != null) {
				id = eventId;
			}

		}
		if (!"".equals(id) && id != null) {
			eventId_binding.setValue(id);
			eventId_binding.repaint();

			List<Minutes> minutes = minutersServce.getMinutesByEvent(id);

			if (minutes != null && minutes.size() > 0) {
				str.append("<div id=\"minDiv\" style=\"overflow-y:scroll;word-break:break-all;height:200px;\">");
				str.append("<ul>");
				for (int i = 0; i < minutes.size(); i++) {
					Minutes mt = minutes.get(i);
					// System.out.println("-----:" + mt.getMinutes());
					String minutesContent = mt.getMinutes().replaceAll(
							"<(/?\\S+)\\s*?[^<]*?(/?)>", "<$1$2>");
					// System.out.println("-----11:" + minutesContent);

					SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat
							.getInstance();
					formatter.applyPattern("yyyy-MM-dd HH:mm:ss");
					str.append("<li style=\"line-height:260%\">");
					str.append("<font color=\"#000099\" size=\"3\">");
					str.append(" [" + formatter.format(mt.getMinutesDate())
							+ "] ");
					str.append(minutesContent + ";</font>&nbsp;");

					str.append("<a href=\"javascript:updateMinute('"
							+ mt.getId() + "');\">");

					str
							.append("<font color=\"#000099\" size=\"3\" style=\"border:double\">编辑</font>");
					str.append("</a>");

					str.append("</li>");
				}
				str.append("</ul></div>");
			}
		}
		return str.toString();
	}

	@Action(id = "saveRepair")
	public void saveRepair() {
		Minutes min = new Minutes();
		min.setId(IdUtils.getUUID());
		if(minutesContent.startsWith("&nbsp;")){
			min.setMinutes(minutesContent);
		}else{
			minutesContent = minutesContent.replaceAll("<P>","");
			minutesContent = minutesContent.replaceAll("</P>","");
			min.setMinutes("&nbsp;"+minutesContent);
			
		}
		min.setMinutesDate(new Date());
		min.setMinutes_DelFlag(false);
		min.setCreator(SecurityUserHolder.getCurrentUserId());

		if (eventId != null) {
			Event event = eventService.getEventById(eventId);
			if (event != null)
				min.setSiEvent(event);
		}
		minutersServce.saveMinutes(min);
		minutesList = getMinutesList();

		Browser.execClientScript("clearMinuteContent();refDiv();");
	}
	
	@Action(id = "saveTextRepaire")
	public void saveTextRepaire() {
		Minutes min = new Minutes();
		min.setId(IdUtils.getUUID());
		eventId = context.getExternalContext().getRequestParameterMap().get("eventId");
		minutesContent = context.getExternalContext().getRequestParameterMap().get("minutesContent");
		if(minutesContent.startsWith("&nbsp;")){
			min.setMinutes(minutesContent);
		}else{
			minutesContent = minutesContent.replaceAll("<P>","");
			minutesContent = minutesContent.replaceAll("</P>","");
			min.setMinutes("&nbsp;"+minutesContent);
			
		}
		min.setMinutesDate(new Date());
		min.setMinutes_DelFlag(false);
		min.setCreator(SecurityUserHolder.getCurrentUserId());

		if (eventId != null) {
			Event event = eventService.getEventById(eventId);
			if (event != null)
				min.setSiEvent(event);
		}
		minutersServce.saveMinutes(min);
		
		minutesList = "";
		minutesList_binding.repaint();

		minutesList = this.getMinutesList();
		
		Browser.execClientScript("clearMinuteContent();refDiv();");
	}

	
	
	@Action(id = "saveEvent")
	public void saveEvent() {
		Event event = new Event();
		event.setId(IdUtils.getUUID());
		event.setEventName(eventTitle_value);

		event.setEventCreateDate(new Date());
		event.setEventCreateUser(SecurityUserHolder.getCurrentUserId());
		event.setEvent_DelFlag(false);

		eventService.saveEvent(event);
		Browser
				.execClientScript("eventWinJsvar.hide();window.parent.refreshMainPage()");

	}

	/*
	 * 修改会议记录
	 * 
	 * 隐藏窗口，刷新会议记录列表
	 */
	@Action(id = "updateMinuate")
	public void updateMinuate() {
		Minutes min = minutersServce.getMinutesById(minId);
		if (min != null) {
			if (uMinCon != null && !"<P>&nbsp;</P>".equals(uMinCon)) {
				min.setMinutes(uMinCon);
				minutersServce.saveMinutes(min);
			} else {
				min.setMinutes_DelFlag(true);
				minutersServce.saveMinutes(min);
			}
		}
		Browser.execClientScript("updateMinWinJsvar.hide();");

		minutesList = getMinutesList();
		
		Browser.execClientScript("refDiv();");
	}

	@Action(id = "showUpdateMin")
	public void showUpdateMin() {
		String minId = context.getExternalContext().getRequestParameterMap()
				.get("minId");
		if (minId != null && !"".equals(minId)) {
			Minutes min = minutersServce.getMinutesById(minId);
			minId_binding.setValue(minId);
			minId_binding.repaint();
			if (min.getMinutes() != null && !"".equals(min.getMinutes())) {
				uMinCon_binding.setValue(min.getMinutes());
				uMinCon_binding.repaint();
			}

			Browser.execClientScript("updateMinWinJsvar.show();");

		}
	}
}
